package com.jusu.dao;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import org.apache.ibatis.session.SqlSession;

import com.jusu.util.MyBatisUtil;

public class BaseDaoImpl {

	public Object excute(String methodname)
	{
		return excute(methodname,null);
	}
	
	
	public Object excute(String methodname,Object param)
	{
		SqlSession session =MyBatisUtil.getSession();
		String daoname =this.getClass().getGenericInterfaces()[0].getTypeName();
		Class daoclass=null;
		try {
			daoclass = Class.forName(daoname);
		} catch (ClassNotFoundException e1) {
			e1.printStackTrace();
		}
		Object daoNew = session.getMapper(daoclass);
		Method method =null;
		Object result =null;
		try {
			if(param==null)
			{
				 method = daoclass.getMethod(methodname);
				 result =method.invoke(daoNew);
				 session.close();
				
			}else {
				 method = daoclass.getMethod(methodname, param.getClass());
				 result =method.invoke(daoNew, param);
				 session.close();
			}
			
		} catch (NoSuchMethodException e) {
			e.printStackTrace();
		} catch (SecurityException e) {
			e.printStackTrace();
		}catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		}
		
		return result;
	}
	
	public Object excute()
	{
		return excute(null);
	}
	
	public Object excute(Object param)
	{
		String methodname = getmethodinner();
		SqlSession session =MyBatisUtil.getSession();
		String daoname =this.getClass().getGenericInterfaces()[0].getTypeName();
		Class daoclass=null;
		try {
			daoclass = Class.forName(daoname);
		} catch (ClassNotFoundException e1) {
			e1.printStackTrace();
		}
		Object daoNew = session.getMapper(daoclass);
		Method method =null;
		Object result =null;
		try {
			if(param==null)
			{
				 method = daoclass.getMethod(methodname);
				 result =method.invoke(daoNew);
				
			}else {
				 method = daoclass.getMethod(methodname, param.getClass());
				 result =method.invoke(daoNew, param);
			}
			
		} catch (NoSuchMethodException e) {
			e.printStackTrace();
		} catch (SecurityException e) {
			e.printStackTrace();
		}catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		}
		
		return result;
	}
	
	public String getmethod()
	{
		return new 	Exception().getStackTrace()[1].getMethodName();
	}
	
	private String getmethodinner()
	{
		return new 	Exception().getStackTrace()[2].getMethodName();
	}
}
